﻿using System;
using System.Data;
using System.Data.Odbc;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using BTS.DB;
using BTS.Entity;
using BTS.Util;

namespace BTS.Page
{


    public partial class CourseManage : System.Web.UI.Page
    {
        public string actPage = "list";
        public StringBuilder outBuf = new StringBuilder();
        public StringBuilder outBuf2 = new StringBuilder();
        public String targetID;
        public Course theCourse;
        public List<Course> listCourse;

        public Room[] roomList;
        public Teacher[] teacherList;

        public string errorText = "";
        public CultureInfo ci = new CultureInfo("en-US");
        public Logger log = Logger.GetLogger(Config.MAINLOG);
    //    protected System.Web.UI.HtmlControls.HtmlInputFile portrait;
  

        protected void Page_Load(object sender, EventArgs e)
        {
            // Authentication
            string redirect = VerifyAA.Verify(Session
                , Request
                , Response
                , "NoRight.aspx");

            // Collect paramters
            actPage = Request.Form.Get("actPage");
            if (actPage == null) actPage = Request["actPage"];
            targetID = Request.Form.Get("targetID");
            if (targetID == null) targetID = Request["targetID"];

            // log
            log.StampLine(Logger.DETAILED, "Request [" + Request["ASP.NET_SessionId"] + "][" + Request.RawUrl + "][actPage=" + actPage + "&targetID=" + targetID + "]");
            log.StampLine(Logger.DEBUG, "Param [" + Request["ASP.NET_SessionId"] + "][" + Request.Params.ToString() + "]");


                if ((actPage == null) || (actPage.Trim().Length==0) || (actPage.Equals("list")))
                {
                    string qSearch = Request.Form.Get("qsearch");
                    bool isNewSearch = false;
                    if (qSearch != null)
                    {
                        isNewSearch = true;
                    }
                    else
                    {
                        qSearch = Request["qsearch"];
                    }
                    DoListCourse(qSearch, isNewSearch);
                }
                else if (actPage.Equals("view"))
                {
                    targetID = Request["targetID"];
                    DoViewCourse(targetID);
                }
                else if (actPage.Equals("add"))
                {
                    DoAddCourse();
                }
                else if (actPage.Equals("add_submit"))
                {
                    DoAddSubmitCourse();
                    Response.Redirect("CourseManage.aspx");
                }
                else if (actPage.Equals("edit"))
                {
                    targetID = Request["targetID"];
                    DoEditCourse(targetID);
                }
                else if (actPage.Equals("edit_submit"))
                {
                    targetID = Request["targetID"];
                    DoEditSubmitCourse(targetID);
                    Response.Redirect("CourseManage.aspx");
                }
                else if (actPage.Equals("delete"))
                {
                    targetID = Request["targetID"];
                    DoDeleteCourse(targetID);
                    Response.Redirect("CourseManage.aspx");
                }
        }

        protected void DoViewCourse(string courseID)
        {
            DBManager db = new MySQLDBManager(Config.DB_SERVER, Config.DB_NAME, Config.DB_USER, Config.DB_PASSWORD);
            theCourse = new Course();
            theCourse.LoadFromDB(db, " course_id=" + courseID);
            theCourse.LoadTeacher(db);
            int regisCount = theCourse.GetRegistrationCount(db);
            db.Close();

            TextReader reader = new StreamReader(Config.PATH_APP_ROOT + "\\template\\course_view.htm");
            String templateContent = reader.ReadToEnd();
            reader.Close();

            String htmlContent =
                String.Format(templateContent
                    , Config.URL_PIC_COURSE + "/" + theCourse._img                    
                    , theCourse._btsCourseID + " " + theCourse._courseName
                    , theCourse._shortName
                    , theCourse._category
                    , theCourse._startdate.ToString("dd/MM/yyyy", ci) + " - " + theCourse._enddate.ToString("dd/MM/yyyy", ci) + "<br>"
                      + theCourse._dayOfWeek + " " + theCourse._starttime.ToString("HH:mm", ci) + " - " + theCourse._endtime.ToString("HH:mm", ci)
                    , theCourse._teacher._firstname + " " + theCourse._teacher._surname
                    , StringUtil.Int2StrComma(theCourse._cost)
                    , theCourse._seatLimit.ToString()
                    , theCourse._bankRegisLimit.ToString()
                    , regisCount.ToString()
                    , theCourse._courseDesc);

            outBuf.Append(htmlContent);

        }
        
        protected void DoListCourse(string searchStr, bool isNewSearch)
        {
            // get Page
            int pg = 1;
            if ((!isNewSearch) && (Request["pg"] != null)) pg = Int32.Parse(Request["pg"]);

            string[,] bgclass = new string[,] { { "class=\"spec\"", "class=\"td1\"" }, { "class=\"specalt\"", "class=\"alt\"" } };

            listCourse = new List<Course>();
            DBManager db = new MySQLDBManager(Config.DB_SERVER, Config.DB_NAME, Config.DB_USER, Config.DB_PASSWORD);
            
            
            string qSearchSQL = Course.GetQSearchSQL(searchStr);
            if (qSearchSQL.Trim().Length > 0) qSearchSQL = " WHERE " + qSearchSQL;
            int numRec = db.QueryCount("SELECT Count(*) FROM course c " + qSearchSQL);

            // add join condition
            qSearchSQL = qSearchSQL + ((qSearchSQL.Trim().Length > 0)?" AND ":" WHERE ") + " c.teacher_id=t.teacher_id";

            OdbcDataReader reader = db.Query("SELECT c.*,t.firstname as teacher_firstname, t.surname as teacher_surname FROM course c, teacher t " 
                + qSearchSQL + " LIMIT " + Config.TBRECORD_PER_PAGE + " OFFSET " + (((pg - 1) * Config.TBRECORD_PER_PAGE)));
            int i = 0;
            while (reader.Read())
            {
                Course course = Course.CreateForm(reader);
                // byte[] raw = Encoding.Default.GetBytes(course._firstname);
                // course._firstname = Encoding.GetEncoding("tis-620").GetString(raw);

                string divtxt = Config.URL_PIC_COURSE + "/" + course._img;

                outBuf.Append("<tr>");
                outBuf.Append("<th scope=\"row\" abbr=\"Model\" " + bgclass[i % 2, 0] + ">" + course._btsCourseID + "</th>");
                outBuf.Append("<td " + bgclass[i % 2, 1] + "  ><a href=\"CourseManage.aspx?actPage=view&targetID=" + course._courseID + "\" >"
                    + "<b>" + course._courseName + "</b></a><br>"
                    + course._courseDesc
                    + "</td>");
                outBuf.Append("<td " + bgclass[i % 2, 1] + " align=center>" + course._cost + "&nbsp</td>");
                outBuf.Append("<td " + bgclass[i % 2, 1] + "  align=center>" 
                    + course._startdate.ToString("dd/MM/yyyy", ci) + " - " +  course._enddate.ToString("dd/MM/yyyy", ci) + "<br>"
                    + course._dayOfWeek + " " + course._starttime.ToString("HH:mm",ci) + " - " + course._endtime.ToString("HH:mm",ci)
                    +  "&nbsp</td>");
                outBuf.Append("<td " + bgclass[i % 2, 1] + "  >" + course._teacher._firstname + " " + course._teacher._surname + "&nbsp</td>");
                outBuf.Append("<td " + bgclass[i % 2, 1] + "  align=center>&nbsp");
                outBuf.Append("<a href=\"javascript:setVal('actPage','edit');setVal('targetID','" + course._courseID + "');doSubmit()\"><img src=\"img/sys/edit.gif\" border=0 alt=\"Edit\"></a>&nbsp");
                outBuf.Append("<a href=\"javascript:if (confirm('Delete this course?')) { setVal('actPage','delete');setVal('targetID','" + course._courseID + "');doSubmit(); }\"><img src=\"img/sys/delete.gif\" border=0 alt=\"Delete\"></a>&nbsp");
 
                outBuf.Append("</td>");
                outBuf.Append("</tr>\n");

                i++;
            }
            db.Close();
            
            // calculate max page            
            int maxpg = numRec / Config.TBRECORD_PER_PAGE;
            if (maxpg < 1) { maxpg = 1; }
            else if (numRec % Config.TBRECORD_PER_PAGE > 0) { maxpg++; }
            // Generate Page Navi HTML
            outBuf2.Append("<b>Page</b>  ");
            for (i = 1; i <= maxpg; i++)
            {
                if (i == pg) { outBuf2.Append("<b>"+i+"</b> "); }
                else {
                    outBuf2.Append(String.Format("<a href=\"CourseManage.aspx?pg={0}&qsearch={1}\">{0}</a> ", i.ToString(), searchStr));
                }

            }
            
          //  <a href="#">1</a> <b>2</b> <a href="#">3</a> <a href="#">4</a>


        }

        public void DoAddCourse()
        {
            DBManager db = new MySQLDBManager(Config.DB_SERVER, Config.DB_NAME, Config.DB_USER, Config.DB_PASSWORD);
            roomList = Room.LoadListFromDBCustom(db, "SELECT r.room_id, r.name, b.branch_name as branch_name FROM room r, branch b WHERE r.branch_id=b.branch_id");
            teacherList = Teacher.LoadListFromDB(db, " ORDER BY firstname");
            db.Close();
        }

        protected void DoAddSubmitCourse()
        {
            Course c = new Course();
            
            // validate data
            c._btsCourseID = Request["bts_course_id"];
            c._courseName = Request["course_name"];
            c._shortName = Request["short_name"];
            c._courseDesc = Request["course_desc"];
            c._roomID = Int32.Parse(Request["room_id"]);
            c._teacherID = Int32.Parse(Request["teacher_id"]);            
            c._category = Request["category"];

            c._startdate = StringUtil.getDate(Request["startdate"]);
            c._enddate = StringUtil.getDate(Request["enddate"]);
            c._dayOfWeek = Request["day_of_week"];
            c._starttime = StringUtil.getTime(Request["starttime_h"], Request["starttime_m"]);
            c._endtime = StringUtil.getTime(Request["endtime_h"], Request["endtime_m"]);

            c._cost =Int32.Parse(Request["cost"]);
            c._seatLimit = Int32.Parse(Request["seat_limit"]);
            c._bankRegisLimit = 0; // remove field



            c._img = "noimg.jpg";
            if (portrait.PostedFile.FileName != "")
            {
                try
                {
                    string serverFileExt = Path.GetExtension(portrait.PostedFile.FileName);
                    Random rand = new Random((int)DateTime.Now.Ticks);
                    string fullpath = "";
                    string imgname = "";
                    do
                    {
                        string randomFName = rand.Next(Int32.MaxValue).ToString();
                        imgname = randomFName + serverFileExt;
                        fullpath = Config.PATH_APP_ROOT + "\\" + Config.URL_PIC_COURSE + "\\" + imgname;
                    } while (File.Exists(fullpath));

                    portrait.PostedFile.SaveAs(fullpath);
                    c._img = imgname;
                }
                catch (Exception err)
                {
                    errorText = err.Message + err.StackTrace;
                }
            }

            // Save to DB
            DBManager db = new MySQLDBManager(Config.DB_SERVER, Config.DB_NAME, Config.DB_USER, Config.DB_PASSWORD);
            db.Connect();
            db.BeginTransaction(IsolationLevel.ReadCommitted);
            
            c.AddToDB(db);
            c._courseID = Course.GetMaxCourseID(db);

            // Update Payment with empty record
            Payment payment = new Payment();
            payment._courseID = c._courseID;
            payment._sumAllCost = 0;
            payment._sumPaidCost = 0;
            payment._status = 0;
            payment._lastPaidDate = DateTime.Now;
            payment.AddToDB(db);

            db.Commit();
            db.Close();
        }

        public void DoEditCourse(string courseID)
        {
            DBManager db = new MySQLDBManager(Config.DB_SERVER, Config.DB_NAME, Config.DB_USER, Config.DB_PASSWORD);
            theCourse = new Course();
            if (!theCourse.LoadFromDB(db, "course_id=" + courseID)) theCourse = null;

            roomList = Room.LoadListFromDBCustom(db, "SELECT r.room_id, r.name, b.branch_name as branch_name FROM room r, branch b WHERE r.branch_id=b.branch_id");
            teacherList = Teacher.LoadListFromDB(db, " ORDER BY firstname");

            db.Close();

        }

        protected void DoEditSubmitCourse(string courseID)
        {
            Course c = new Course();

            // validate data
            c._courseID = Int32.Parse(courseID);
            c._btsCourseID = Request["bts_course_id"];
            c._courseName = Request["course_name"];
            c._shortName = Request["short_name"];
            c._courseDesc = Request["course_desc"];
            c._roomID = Int32.Parse(Request["room_id"]);
            c._teacherID = Int32.Parse(Request["teacher_id"]);
            c._category = Request["category"];

            c._startdate = StringUtil.getDate(Request["startdate"]);
            c._enddate = StringUtil.getDate(Request["enddate"]);
            c._dayOfWeek = Request["day_of_week"];
            c._starttime = StringUtil.getTime(Request["starttime_h"], Request["starttime_m"]);
            c._endtime = StringUtil.getTime(Request["endtime_h"], Request["endtime_m"]);

            c._cost = Int32.Parse(Request["cost"]);
            c._seatLimit = Int32.Parse(Request["seat_limit"]);
            c._bankRegisLimit = 0; //remove field
            
            // default to old value
            c._img = Request["img_old"];
            if (portrait.PostedFile.FileName != "")
            {
                try
                {
                    string serverFileExt = Path.GetExtension(portrait.PostedFile.FileName);
                    Random rand = new Random((int)DateTime.Now.Ticks);
                    string fullpath = "";
                    string imgname = "";
                    do
                    {
                        string randomFName = rand.Next(Int32.MaxValue).ToString();
                        imgname = randomFName + serverFileExt;
                        fullpath = Config.PATH_APP_ROOT + "\\" + Config.URL_PIC_COURSE + "\\" + imgname;
                    } while (File.Exists(fullpath));

                    portrait.PostedFile.SaveAs(fullpath);
                    c._img = imgname;
                }
                catch (Exception err)
                {
                    errorText = err.Message + err.StackTrace;
                }
            }

            // Save to DB
            DBManager db = new MySQLDBManager(Config.DB_SERVER, Config.DB_NAME, Config.DB_USER, Config.DB_PASSWORD);
            db.Connect();
            c.UpdateToDB(db);
            db.Close();
        }

        protected void DoDeleteCourse(string courseID)
        {
            Course t = new Course();
            t._courseID = Int32.Parse(courseID);
            DBManager db = null;
            try {
                db = new MySQLDBManager(Config.DB_SERVER, Config.DB_NAME, Config.DB_USER, Config.DB_PASSWORD);
                db.Connect();
                
                // Check if payment id paid all
                // If no, unable to delete this course
                // Else
                // Update status=1 (invalid)
                Payment payment = new Payment();
                if (payment.LoadFromDB(db, " course_id=" + courseID))
                {
                    if (payment._sumPaidCost < payment._sumAllCost) // not yet paid all  
                    {
                        errorText = "ยังมีเงินที่เบิกจ่ายไม่หมด " + (payment._sumAllCost - payment._sumPaidCost);
                        return;
                    }
                    else
                    {
                        payment._status = Payment.STATUS_INVALID;
                        payment.UpdateToDB(db);
                    }
                }
                
                // Delete course
                t.DeleteToDB(db);
            } finally {
                if (db!=null) db.Close();
            }
        }
    }
}
